package com.freesun.sys.controller;

import java.util.Date;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.freesun.sys.common.ActiverUser;
import com.freesun.sys.common.ResultObj;
import com.freesun.sys.common.WebUtils;
import com.freesun.sys.domain.Logininfo;
import com.freesun.sys.service.LogininfoService;

@RestController
@RequestMapping("login")
public class LoginController {

	@Autowired
	private LogininfoService logininfoService;
	@RequestMapping("login")
	public ResultObj login(String loginname,String pwd) {
		Subject subject = SecurityUtils.getSubject();
		AuthenticationToken token=new UsernamePasswordToken(loginname,pwd);
		
		try {
			subject.login(token);
			ActiverUser activerUser=(ActiverUser) subject.getPrincipal();
			WebUtils.getSession().setAttribute("user", activerUser.getUser());
			//记录登录日志
			Logininfo entity=new Logininfo();
			entity.setLoginname(activerUser.getUser().getName()+"-"+activerUser.getUser().getLoginname());
			System.out.println("ip:"+WebUtils.getRequest().getRemoteAddr());
			entity.setLoginip(WebUtils.getRequest().getRemoteAddr());
			entity.setLogintime(new Date());
			logininfoService.save(entity);
			return ResultObj.LOGIN_SUCCESS;
		} catch (AuthenticationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return ResultObj.LOGIN_ERROR_PASS;
		}
	}
}
